import re

from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from rider.models import Rider


class RiderSerializer(serializers.ModelSerializer):
    users = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    id_card = serializers.CharField(label="证件号", write_only=True, error_messages={
        "blank": "身份证号不能为空"
    })
    real_name = serializers.CharField(label="真实姓名", error_messages={
        "blank": "姓名不能为空"
    })
    phone = serializers.CharField(label="手机号", error_messages={
        "blank": "手机号不能为空"
    })
    workplace = serializers.CharField(label="工作地点", error_messages={
        "blank": "工作地点不能为空"
    })

    def validate_users(self, users):
        if users.role_type == 2:
            raise serializers.ValidationError("您已注册成为骑手")
        return users

    def validate(self, attrs):
        id_card = attrs.get("id_card")
        phone = attrs.get("phone")
        workplace = attrs.get("workplace")

        if not re.match("^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$", id_card):
            raise serializers.ValidationError("身份证号码非法")
        if not re.match("^1[358]\d{9}$|^147\d{8}$|^176\d{8}$", phone):
            raise serializers.ValidationError("手机号非法")
        if not re.match("^\w+市\w+(区|县)\w+镇$", workplace):
            raise serializers.ValidationError("地址格式不正确(xx市xx区/县xx镇)")

        return attrs

    def is_valid(self, raise_exception=False):
        try:
            super().is_valid(raise_exception=True)
        except Exception as e:
            assert isinstance(e, ValidationError)
            for k, v in e.detail.items():
                raise ValidationError({"err_msg": v[0]})

    class Meta:
        model = Rider
        fields = "__all__"
